package com.roadjava.rbac.security.handler;

import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.util.ResponseUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ExceptionTranslationFilter出现访问拒绝异常AccessDeniedException时(403状态码)会回调handle方法
 * 访问拒绝处理
 * @author zhaodaowen
 *
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 提取无权限原因
        String reason = accessDeniedException.getMessage() != null ? accessDeniedException.getMessage() : "无详细信息";

        // 创建包含原因的结果对象
        Result<String> result = Result.buildFailure("无权访问: " + reason);

        // 返回JSON格式的响应
        ResponseUtil.respAppJson(response, result);
    }
}
